package lishizheng.demo02;


import org.apache.commons.io.FileUtils;

import java.io.File;
import java.io.IOException;
import java.net.URL;
import java.util.concurrent.*;

//线程创建3：实现Callable接口
/*
*
* */
public class TestCallable implements Callable<Boolean> {
    private String url; //网络图片地址
    private String name; //保存的文件名

    public TestCallable(String url, String name){
        this.url = url;
        this.name = name;
    }

    //下载图片线程的执行体
    @Override
    public Boolean call() {
        WebDownLoader webDownLoader = new WebDownLoader();
        webDownLoader.downloader(url,name);
        System.out.println("已下载文件名为：" + name + "的图片");
        return true;
    }


    public static void main(String[] args) throws ExecutionException, InterruptedException {
        //确保图片ulr是正确的
        TestCallable t2 = new TestCallable("https://img-blog.csdnimg.cn/20210228094648502.png","我的博客图片02.png");
        TestCallable t3 = new TestCallable("https://img-blog.csdnimg.cn/20210303104522231.png","我的博客图片03.png");
        TestCallable t1 = new TestCallable("https://img-blog.csdnimg.cn/20210210194321356.png","我的博客图片01.png");

        //创建执行服务
        ExecutorService ser = Executors.newFixedThreadPool(3);

        //提交执行
        Future<Boolean> r1 = ser.submit(t1);
        Future<Boolean> r2 = ser.submit(t2);
        Future<Boolean> r3 = ser.submit(t3);

        //获取结果
        boolean res1 = r1.get();
        boolean res2 = r2.get();
        boolean res3 = r3.get();

        //关闭服务
        ser.shutdown();

    }
}


//下载器
class  WebDownLoader{
    //下载方法
    public void downloader(String  url, String  name){
        try {
            FileUtils.copyURLToFile(new URL(url), new File(name)); //调用FileUtils类中的copyURLToFile方法实现下载
        } catch (IOException e) {
            e.printStackTrace();
            System.out.println("IO异常：downloader方法出现问题");
        }
    }
}
